package ca.etsmtl.log660.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import ca.etsmtl.log660.configuration.SessionFactoryHelper;
import ca.etsmtl.log660.entity.Client;

class ClientDAO {
	
	private static final String FIND_BY_CREDENTIAL = "findByCredential";
	private static final String FIND_BY_CREDENTIAL_EMAIL_PARAM = "email";
	private static final String FIND_BY_CREDENTIAL_PASSWORD_PARAM = "password";

	@SuppressWarnings("unchecked")
	public Client getByCredential(String email, String password) {
		Client loggedClient = null;
		
		Session session = SessionFactoryHelper.getSessionFactory().openSession();
		session.beginTransaction();
		Query query = session.getNamedQuery(FIND_BY_CREDENTIAL);
		query.setString(FIND_BY_CREDENTIAL_EMAIL_PARAM, email);
		query.setString(FIND_BY_CREDENTIAL_PASSWORD_PARAM, password);
		List<Client> result = query.list();
		if (result.size() == 1) {
			loggedClient = result.get(0);
		}
		session.getTransaction().commit();
		session.close();
		
		return loggedClient;
	}
	
	public Client getById(Long id) {
		Client client = null;
		
		Session session = SessionFactoryHelper.getSessionFactory().openSession();
		session.beginTransaction();
		client = (Client) session.get(Client.class, id);
		session.getTransaction().commit();
		session.close();

		return client;
	}
}
